package cn.hd01.export;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.hd01.export.anno.Support;

import com.google.common.io.Closeables;
import com.google.common.io.Files;

@Component
public class ImporterDelegate {
	private Map<String, Importer> exporters = new HashMap<String, Importer>();

	@Autowired(required = false)
	public void setExporters(List<Importer> exports) {
		if (CollectionUtils.isEmpty(exports)) {
			return;
		}

		for (Importer exporter : exports) {
			if (!exporter.getClass().isAnnotationPresent(Support.class)) {
				continue;
			}
			String[] exts = exporter.getClass().getAnnotation(Support.class).value();
			if (exts == null) {
				continue;
			}

			for (String ext : exts) {
				this.exporters.put(ext, exporter);
			}
		}
	}

	public <T> void importer(File file, RowProccess<T> process) throws Exception {
		String ext = Files.getFileExtension(file.getAbsolutePath());

		Importer exporter = exporters.get(ext);
		if (exporter == null) {
			throw new UnsupportedOperationException("不支持该文件类型 " + ext);
		}

		FileInputStream is = new FileInputStream(file);
		try {
			exporter.importer(is, process);
		} finally {
			Closeables.closeQuietly(is);
		}
	}

	public <T> void asyncImporter(File file, RowProccess<T> process) throws Exception {
		importer(file, process);
	}

}
